﻿
using UnityEngine;
using UnityEngine.UI;
using System.IO;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Diagnostics;
using System.Text;
using Jinndev.UI;
using Debug = UnityEngine.Debug;

namespace Jinndev {

    public class MainUI : BaseUIBehaviour {

        #region static
        public static readonly string PATH = "Prefab/UI/Main/MainUI";

        public static MainUI Create() {
            return UIManager.Instance.Add<MainUI>(PATH, UIParam.FullScreen);
        }
        #endregion


        public GameObject updateLoading;
        public GameObject updateButton;
        public GameObject checkUpdateButton;
        public Text versionText;

        private Process curProcess;
        private Thread curThread;



        private void Awake() {
            versionText.text = Application.version;
            updateLoading.SetActive(false);
            updateButton.SetActive(false);
            checkUpdateButton.SetActive(true);
        }

        private IEnumerator Start() {
            if (!Application.isEditor) {
                // 根据启动位置(包括快捷方式)，自动选择合适的项目
                if (Setting.Instance.projectPathList != null && Setting.Instance.projectPathList.Count > 1) {
                    string startPath = Util.GetStartPath();
                    if (!string.IsNullOrEmpty(startPath)) {
                        foreach (string projectPath in Setting.Instance.projectPathList) {
                            if (startPath.StartsWith(projectPath)) {
                                Setting.Instance.projectPath = projectPath;
                                break;
                            }
                        }
                    }
                }

                yield return new WaitForSeconds(1);
                //OnClickCheckUpdate();
            }
        }

        private void OnDestroy() {
            AbortCurThread();
        }

        private void Update() {
            TryInvokeAllActions();
        }

        public void OnClickUpdate() {
            if (Application.isEditor) {
                NotificationUI.Create("不能在编辑器运行");
                return;
            }
            string rootDir = new FileInfo(Application.dataPath).Directory.FullName;
            string updaterExe = Path.Combine(rootDir, "Updater.exe");

            if (!File.Exists(updaterExe)) {
                DialogUI.Create("Error", "Updater 不存在");
                return;
            }

            string exeName;
            try {
                exeName = Path.GetFileNameWithoutExtension(Process.GetCurrentProcess().MainModule.FileName);
            }
            catch (System.Exception e) {
                NotificationUI.Create(e.Message);
                return;
            }

            var startInfo = CommonUtil.CreateProcessStartInfo(updaterExe, $"-exe {exeName}");
            startInfo.CreateNoWindow = false;

            NotificationUI.Create("检查更新");
            //Process.Start(startInfo);
            ThreadPool.QueueUserWorkItem((a) => {
                Process.Start(startInfo);
            });
        }

        public void OnClickCheckUpdate() {
            //if (Application.isEditor) {
            //    NotificationUI.Create("不能在编辑器运行");
            //    return;
            //}
            string rootDir = new FileInfo(Application.dataPath).Directory.FullName;
            string updaterExe = Path.Combine(rootDir, "Updater.exe");

            if (!File.Exists(updaterExe)) {
                DialogUI.Create("Error", "Updater 不存在");
                return;
            }


            NotificationUI.Create("检查更新");
            checkUpdateButton.SetActive(false);
            updateLoading.SetActive(true);

            StartThread(() => {
                StringBuilder builder = null;
                PublishInfo publishInfo = null;
                string errorText = null;

                CommonUtil.StartProcess(updaterExe, $"-c", Encoding.GetEncoding("GBK"), (text) => {
                    text = text.Trim();

                    if (text.EndsWith("[PublishInfo] Start")) {
                        builder = new StringBuilder();
                    }
                    else if (text.EndsWith("[PublishInfo] End")) {
                        builder.Append(text.Substring(0, text.Length - "[PublishInfo] End".Length));

                        publishInfo = Json.JsonUtil.Deserialize<PublishInfo>(builder.ToString());
                        builder = null;
                    }
                    else if (builder != null) {
                        builder.Append(text);
                    }
                    else if (text.StartsWith("[Error]")) {
                        errorText = text;
                        Debug.LogError(text);
                    }

                }, (error) => {
                    Debug.LogError(error);
                }, out curProcess);

                Thread.Sleep(200);
                EnqueueAction(() => {
                    OnCheckFinish(publishInfo, errorText);
                });

                curProcess = null;
                curThread = null;
            });
        }

        private void OnCheckFinish(PublishInfo publishInfo, string error) {
            if (publishInfo == null) {
                updateLoading.SetActive(false);
                checkUpdateButton.SetActive(true);
                if (string.IsNullOrEmpty(error)) {
                    NotificationUI.Create("检查更新失败");
                }
                else {
                    NotificationUI.Create(error);
                }
                return;
            }

            bool hasNewVersion = CommonUtil.CompareVersion(Application.version, publishInfo.version) < 0;

            updateLoading.SetActive(false);
            checkUpdateButton.SetActive(!hasNewVersion);
            updateButton.SetActive(hasNewVersion);

            if (hasNewVersion) {
                NotificationUI.Create("发现新版本: " + publishInfo.version);
                versionText.text = $"{Application.version}({publishInfo.version})";
            }
            else {
                NotificationUI.Create("已经是最新版");
            }
        }

        private void StartThread(ThreadStart action) {
            AbortCurThread();
            curThread = new Thread(action);
            curThread.IsBackground = false;
            curThread.Start();
        }

        private void AbortCurThread() {
            if (curProcess != null) {
                curProcess.Kill();
                curProcess = null;
            }
            if (curThread != null && curThread.IsAlive) {
                curThread.Abort();
                curThread = null;
            }
        }

        public void OnCheckCompressBuild() {
            CompressBuildUI.Create();
        }

        public void OnClickCheckCrossRef() {
            CheckCrossRefUI.Create();
        }

        public void OnClickCheckUnusedRes() {
            CheckUnusedResUI.Create();
        }

        public void OnClickMapEditor() {
            ChooseMapUI.Create();
        }

        public void OnClickTcbHosting() {
            TcbHostingUI.Create();
        }

        public void OnClickGenerateTileExcel() {
            OtherUtil.OnClickGenerateTileExcel();
        }

        public void OnClickExportTcbDB() {
            ExportTcbDBUI.Create();
        }

        public void OnClickCopyFile() {
            CopyFileUI.Create();
        }

    }

}
